package cn.tedu.tmallpassport.controller;

import cn.tedu.tmall.common.pojo.authentication.CurrentPrincipal;
import cn.tedu.tmallpassport.pojo.vo.UserLoginResultVO;
import cn.tedu.tmallpassport.service.IUserService;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/Test")
@Api(tags = "2. 测试")
public class UserTestController {
    @Autowired
    IUserService service;

    @GetMapping("/cs")
    @ApiOperation("测试HttpSession登录")
    public String cs(@ApiIgnore HttpSession session){
        Object loginResult = session.getAttribute("loginResult");
        if (loginResult==null){
            return "登录失败,未登录或登录过期";
        }
        return "登录成功"+loginResult;
    }

    @GetMapping("/check-authority")
    @ApiOperation("检查是否有HttpSession权限")
    @ApiOperationSupport(order = 200)
    public String checkAuthority(@ApiIgnore HttpSession session){
        Object Object = session.getAttribute("loginResult");
        if (Object==null){
            return "当前未登录,或登录过期";
        }
        UserLoginResultVO loginResult=(UserLoginResultVO) Object;
        List<String> permissions = loginResult.getPermissions();
        if (!permissions.contains("/admin")){
            return "您当前已经登录，但无此操作权限！";
        }
        return "检查权限通过";
    }

    @GetMapping("/authenticated")
    @ApiOperation("基于Security框架的认证")
    @ApiOperationSupport(order = 300)
    public String authenticated() {
        return "已经通过Spring Security框架的认证！";
    }

    @GetMapping("/principal")
    @ApiOperation("获取当事人的信息")
    @ApiOperationSupport(order = 400)
    public String getPrincipal (@ApiIgnore @AuthenticationPrincipal CurrentPrincipal principal){
        return "当事人ID" + principal.getId() +",当事人用户名" + principal.getUsername();
    }

    @GetMapping("/preAuthorize")
    @PreAuthorize("hasAuthority('/admin')")
    @ApiOperation("基于Security框架的授权")
    @ApiOperationSupport(order = 500)
    public String preAuthorize (){
        return "已经通过Spring Security框架的授权";
    }
}
